-module(testES2).
-include_lib("event_model.hrl").
-export([run/0,run_k/1]).

run_k(A) ->
  [Num|_]=A,
  K = list_to_integer(atom_to_list(Num)),
  run(K).

run() ->
  run(5).

run(K) ->
  Main = self(),
  Rates = get_rates(),
  G = spawn(fun()->event_generator:init(Main, 8000, get_numbers(100000, Rates),Rates,get_sources()) end),
  receive
    _->
      ok
  end,
  Routers = get_routers(K),
  %io:format("Routers:~p~n",[Routers]),
  R = spawn(fun()->router_manager:init(Routers) end),
  spawn(fun()->event_manager:init(Main, R, G, io_lib:format("ES2(K=~p)",[K])) end),
  receive
    finish ->
      finish
  end.

get_numbers(BaseNumber, Rates)->
  get_numbers(Rates, [] , BaseNumber).

get_numbers([], Numbers, _) ->
  lists:reverse(Numbers);

get_numbers([RH|RT], Numbers, BaseNumber) ->
  get_numbers(RT, [(BaseNumber*RH)|Numbers], BaseNumber).


get_rates()->
  [
    1.25*0.7,
    1.25*0.2,
    1.25*0.3,
    1.25*0.25,
    1.25*0.8,
    1.25*0.2
  ].

get_sources()->
  [
    [1,3,31],
    [1,3,4,41],
    [1,2,4,41],
    [2,4,41],
    [3,2,21],
    [3,4,41]
  ].

get_routers(K)->
  R21 = #router{id=21},
  R31 = #router{id=31},
  R41 = #router{id=41},

  B12 = #buffer{dest_id=2,k=K,rate=1.25*8000},
  B13 = #buffer{dest_id=3,k=K,rate=1.25*8000},

  B2e = #buffer{dest_id=21,k=K,rate=1.25*8000},
  B24 = #buffer{dest_id=4,k=K,rate=1.25*8000},

  B32 = #buffer{dest_id=2,k=K,rate=1.25*8000},
  B34 = #buffer{dest_id=4,k=K,rate=1.25*8000},
  B3e = #buffer{dest_id=31,k=K,rate=1.25*8000},

  B4e = #buffer{dest_id=41,k=K,rate=1.25*8000},

  Bs1 = buffers(B13, buffers(B12)),
  Bs2 = buffers(B24, buffers(B2e)),
  Bs3 = buffers(B32, buffers(B34, buffers(B3e))),
  Bs4 = buffers(B4e),

  R1 = router(1, Bs1),
  R2 = router(2, Bs2),
  R3 = router(3, Bs3),
  R4 = router(4, Bs4),

  routers(R4,
    routers(R3,
      routers(R2,
        routers(R1,
          routers(R41,
            routers(R31,
              routers(R21))))))).

buffers(Buffer)->
  buffers(Buffer, dict:new()).

buffers(Buffer, Buffers)->
  #buffer{dest_id=Id} = Buffer,
  dict:store(Id,Buffer, Buffers).

router(Id, Buffers) ->
  #router{id=Id,buffers=Buffers}.

routers(Router)->
  routers(Router,dict:new()).

routers(Router, Routers) ->
  #router{id=Id} = Router,
  dict:store(Id,Router,Routers).
